09 / 10

How do you handle CORS in Next.js Route Handlers?

CORS (Cross-Origin Resource Sharing) in Next.js Route Handlers is handled by manually setting HTTP headers on responses. Unlike Express which has the 'cors' middleware, Next.js Route Handlers require you to set headers explicitly — either per route or globally via a helper function or middleware.

CORS errors occur when a browser blocks a request made from one origin (e.g. http://localhost:3000) to a different origin (e.g. https://api.example.com). In Next.js Route Handlers, you control CORS entirely through response headers — there is no built-in CORS middleware like Express has.

Key CORS Headers You Need to Know
  1. 1

    Access-Control-Allow-Origin — which origins can access the resource (* for all, or specific origin)

  2. 2

    Access-Control-Allow-Methods — which HTTP methods are allowed (GET, POST, PUT, DELETE, OPTIONS)

  3. 3

    Access-Control-Allow-Headers — which request headers are allowed (Content-Type, Authorization)

  4. 4

    Access-Control-Allow-Credentials — whether cookies/auth headers can be sent (true/false)

  5. 5

    Access-Control-Max-Age — how long preflight response can be cached in seconds

  6. 6

    Access-Control-Expose-Headers — which headers are exposed to the browser

Basic CORS on a Single Route Handler
Handling Preflight OPTIONS Request
Reusable CORS Helper Function
Using the CORS Helper in Route Handlers
Global CORS via Middleware (Best for Large Apps)
CORS with Credentials (Cookies and Auth Headers)
NextResponse Helper for Cleaner CORS Responses
Common CORS Mistakes to Avoid
  1. 1

    Forgetting to handle OPTIONS preflight — POST/PUT/DELETE will silently fail in browser

  2. 2

    Using '*' with credentials — browser blocks it, must use exact origin with Allow-Credentials

  3. 3

    Setting CORS headers only on success responses — errors (4xx, 5xx) also need CORS headers or browser won't show the error

  4. 4

    Not including all required headers in Access-Control-Allow-Headers that the client sends

  5. 5

    Hardcoding origins in every route — use a helper or middleware to keep it DRY

  6. 6

    Confusing server-to-server requests with browser requests — CORS only applies to browsers

CORS Strategy Comparison
  1. 1

    Per-route headers — simple, explicit, good for 1-2 routes with different CORS needs

  2. 2

    Shared helper function — DRY, good for medium apps with consistent CORS policy

  3. 3

    Global middleware — best for large apps, applies CORS to all API routes automatically

  4. 4

    next.config.js headers — good for simple static CORS headers but cannot inspect origin dynamically